<template>
  <div class="outbound-container">
    <div class="page-header">
      <button class="back-button" @click="goToHome">
        <span class="icon-arrow-left"></span>
        返回首页
      </button>
      <h1>出库管理</h1>
    </div>
    
    <div class="page-content">
      <!-- 出库申请单 -->
      <div class="form-card">
        <h2>新增出库单</h2>
        
        <form class="outbound-form">
          <div class="form-row">
            <div class="form-group">
              <label>领用部门 <span class="required">*</span></label>
              <select v-model="formData.department">
                <option value="">请选择部门</option>
                <option value="技术部">技术部</option>
                <option value="市场部">市场部</option>
                <option value="行政部">行政部</option>
                <option value="财务部">财务部</option>
                <option value="人力资源部">人力资源部</option>
              </select>
            </div>
            <div class="form-group">
              <label>领用人 <span class="required">*</span></label>
              <input type="text" v-model="formData.applicant" placeholder="请输入领用人姓名">
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>出库日期 <span class="required">*</span></label>
              <input type="date" v-model="formData.outboundDate">
            </div>
            <div class="form-group">
              <label>工单编号</label>
              <input type="text" v-model="formData.workOrderNo" placeholder="关联工单编号（可选）">
            </div>
          </div>
          
          <div class="form-group full-width">
            <label>出库原因</label>
            <textarea v-model="formData.reason" rows="2" placeholder="请输入出库原因"></textarea>
          </div>
          
          <!-- 出库物品明细 -->
          <div class="items-section">
            <div class="section-header">
              <h3>出库物品明细</h3>
              <button type="button" class="add-item-btn" @click="addItemRow">
                <span class="icon-plus">+</span> 添加物品
              </button>
            </div>
            
            <table class="items-table">
              <thead>
                <tr>
                  <th>耗材名称 <span class="required">*</span></th>
                  <th>规格型号</th>
                  <th>单位</th>
                  <th>库存数量</th>
                  <th>出库数量 <span class="required">*</span></th>
                  <th>用途</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in formData.items" :key="index">
                  <td>
                    <select 
                      v-model="item.consumableId" 
                      @change="handleConsumableChange(item, index)"
                    >
                      <option value="">请选择耗材</option>
                      <option 
                        v-for="consumable in consumables" 
                        :key="consumable.id" 
                        :value="consumable.id"
                      >
                        {{ consumable.name }}
                      </option>
                    </select>
                  </td>
                  <td>{{ item.specification }}</td>
                  <td>{{ item.unit }}</td>
                  <td>{{ item.stockQuantity }}</td>
                  <td>
                    <input 
                      type="number" 
                      v-model="item.quantity" 
                      min="1"
                      @input="checkQuantity(item)"
                    >
                    <span v-if="item.quantity > item.stockQuantity" class="error-text">
                      超出库存
                    </span>
                  </td>
                  <td>
                    <input type="text" v-model="item.purpose" placeholder="用途">
                  </td>
                  <td>
                    <button 
                      type="button" 
                      class="delete-item-btn" 
                      @click="deleteItemRow(index)"
                      :disabled="formData.items.length <= 1"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <div class="form-actions">
            <button type="button" class="reset-btn" @click="resetForm">重置</button>
            <button type="button" class="submit-btn" @click="submitOutbound">提交出库单</button>
          </div>
        </form>
      </div>
      
      <!-- 出库记录列表 -->
      <div class="records-card">
        <div class="card-header">
          <h2>出库记录列表</h2>
          <div class="search-box">
            <input 
              type="text" 
              v-model="searchKeyword" 
              placeholder="搜索单号、部门或领用人..."
            >
            <button class="search-btn" @click="searchRecords">搜索</button>
          </div>
        </div>
        
        <table class="records-table">
          <thead>
            <tr>
              <th>出库单号</th>
              <th>领用部门</th>
              <th>领用人</th>
              <th>出库日期</th>
              <th>物品总数</th>
              <th>操作人</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="record in filteredRecords" :key="record.id">
              <td>{{ record.outboundNo }}</td>
              <td>{{ record.department }}</td>
              <td>{{ record.applicant }}</td>
              <td>{{ formatDate(record.outboundDate) }}</td>
              <td>{{ record.totalItems }}</td>
              <td>{{ record.operator }}</td>
              <td>
                <span class="status-tag" :class="record.status === '已完成' ? 'status-completed' : 'status-canceled'">
                  {{ record.status }}
                </span>
              </td>
              <td>
                <button class="view-btn" @click="viewRecord(record)">查看</button>
                <button 
                  class="cancel-btn" 
                  @click="cancelRecord(record.id)"
                  v-if="record.status === '已完成'"
                >
                  取消
                </button>
              </td>
            </tr>
            <tr v-if="filteredRecords.length === 0">
              <td colspan="8" class="no-data">暂无出库记录</td>
            </tr>
          </tbody>
        </table>
        
        <div class="pagination">
          <button :disabled="currentPage === 1" @click="currentPage--">上一页</button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button :disabled="currentPage === totalPages" @click="currentPage++">下一页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OutboundManage',
  data() {
    return {
      // 耗材数据
      consumables: [
        {
          id: 1,
          name: '打印机墨盒',
          specification: 'HP-12A',
          unit: '个',
          stock: 15
        },
        {
          id: 2,
          name: '复印纸',
          specification: 'A4-70g',
          unit: '箱',
          stock: 30
        },
        {
          id: 3,
          name: 'U盘',
          specification: '32GB',
          unit: '个',
          stock: 8
        },
        {
          id: 4,
          name: '鼠标',
          specification: '无线',
          unit: '个',
          stock: 3
        },
        {
          id: 5,
          name: '键盘',
          specification: '机械',
          unit: '个',
          stock: 0
        }
      ],
      
      // 出库单表单数据
      formData: {
        department: '',
        applicant: '',
        outboundDate: new Date().toISOString().split('T')[0],
        workOrderNo: '',
        reason: '',
        items: [
          {
            consumableId: '',
            name: '',
            specification: '',
            unit: '',
            stockQuantity: 0,
            quantity: 1,
            purpose: ''
          }
        ]
      },
      
      // 出库记录
      outboundRecords: [
        {
          id: 1,
          outboundNo: 'OUT20230516001',
          department: '技术部',
          applicant: '王五',
          outboundDate: '2023-05-16',
          workOrderNo: 'WO20230516001',
          reason: '维修设备使用',
          totalItems: 2,
          operator: '张三',
          status: '已完成',
          items: [
            { name: '打印机墨盒', specification: 'HP-12A', quantity: 2, unit: '个' },
            { name: 'U盘', specification: '32GB', quantity: 1, unit: '个' }
          ]
        },
        {
          id: 2,
          outboundNo: 'OUT20230510001',
          department: '行政部',
          applicant: '赵六',
          outboundDate: '2023-05-10',
          workOrderNo: '',
          reason: '日常办公使用',
          totalItems: 1,
          operator: '李四',
          status: '已完成',
          items: [
            { name: '复印纸', specification: 'A4-70g', quantity: 10, unit: '箱' }
          ]
        }
      ],
      
      // 搜索和分页
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {
    filteredRecords() {
      const filtered = this.outboundRecords.filter(record => 
        record.outboundNo.includes(this.searchKeyword) ||
        record.department.includes(this.searchKeyword) ||
        record.applicant.includes(this.searchKeyword)
      );
      
      return filtered.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    totalPages() {
      const filteredCount = this.outboundRecords.filter(record => 
        record.outboundNo.includes(this.searchKeyword) ||
        record.department.includes(this.searchKeyword) ||
        record.applicant.includes(this.searchKeyword)
      ).length;
      
      return Math.ceil(filteredCount / this.pageSize);
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    
    // 添加物品行
    addItemRow() {
      this.formData.items.push({
        consumableId: '',
        name: '',
        specification: '',
        unit: '',
        stockQuantity: 0,
        quantity: 1,
        purpose: ''
      });
    },
    
    // 删除物品行
    deleteItemRow(index) {
      this.formData.items.splice(index, 1);
    },
    
    // 选择耗材变化
    handleConsumableChange(item, index) {
      const consumable = this.consumables.find(c => c.id === parseInt(item.consumableId));
      if (consumable) {
        this.$set(this.formData.items, index, {
          ...this.formData.items[index],
          name: consumable.name,
          specification: consumable.specification,
          unit: consumable.unit,
          stockQuantity: consumable.stock,
          quantity: 1
        });
      } else {
        this.$set(this.formData.items, index, {
          ...this.formData.items[index],
          name: '',
          specification: '',
          unit: '',
          stockQuantity: 0
        });
      }
    },
    
    // 检查出库数量
    checkQuantity(item) {
      if (item.quantity > item.stockQuantity) {
        // 可以在这里添加提示或自动修正
      }
    },
    
    // 重置表单
    resetForm() {
      if (confirm('确定要重置表单吗？所有已输入的数据将丢失。')) {
        this.formData = {
          department: '',
          applicant: '',
          outboundDate: new Date().toISOString().split('T')[0],
          workOrderNo: '',
          reason: '',
          items: [
            {
              consumableId: '',
              name: '',
              specification: '',
              unit: '',
              stockQuantity: 0,
              quantity: 1,
              purpose: ''
            }
          ]
        };
      }
    },
    
    // 提交出库单
    submitOutbound() {
      // 表单验证
      if (!this.formData.department || !this.formData.applicant || !this.formData.outboundDate) {
        alert('请填写部门、领用人和出库日期');
        return;
      }
      
      // 检查物品明细
      for (const item of this.formData.items) {
        if (!item.consumableId) {
          alert('请选择所有耗材');
          return;
        }
        
        if (!item.quantity || item.quantity < 1) {
          alert('出库数量必须大于0');
          return;
        }
        
        if (item.quantity > item.stockQuantity) {
          alert(`"${item.name}" 出库数量超出库存`);
          return;
        }
      }
      
      // 生成出库单号
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const serial = String(this.outboundRecords.length + 1).padStart(3, '0');
      const outboundNo = `OUT${year}${month}${day}${serial}`;
      
      // 创建出库记录
      const newRecord = {
        id: this.outboundRecords.length + 1,
        outboundNo,
        ...this.formData,
        totalItems: this.formData.items.reduce((sum, item) => sum + item.quantity, 0),
        operator: '当前用户',
        status: '已完成',
        items: this.formData.items.map(item => ({
          name: item.name,
          specification: item.specification,
          quantity: item.quantity,
          unit: item.unit
        }))
      };
      
      // 更新库存
      this.formData.items.forEach(item => {
        const index = this.consumables.findIndex(c => c.id === parseInt(item.consumableId));
        if (index !== -1) {
          this.consumables[index].stock -= item.quantity;
        }
      });
      
      // 添加到记录列表
      this.outboundRecords.unshift(newRecord);
      
      // 重置表单
      this.resetForm();
      
      alert('出库单提交成功！');
    },
    
    // 搜索记录
    searchRecords() {
      this.currentPage = 1; // 重置到第一页
    },
    
    // 查看记录详情
    viewRecord(record) {
      let detailText = `出库单: ${record.outboundNo}\n`;
      detailText += `领用部门: ${record.department}\n`;
      detailText += `领用人: ${record.applicant}\n`;
      detailText += `出库日期: ${this.formatDate(record.outboundDate)}\n`;
      detailText += `工单编号: ${record.workOrderNo || '无'}\n`;
      detailText += `出库原因: ${record.reason || '无'}\n`;
      detailText += `操作人: ${record.operator}\n`;
      detailText += `状态: ${record.status}\n\n`;
      detailText += `出库物品:\n`;
      
      record.items.forEach((item, index) => {
        detailText += `${index + 1}. ${item.name} (${item.specification}): ${item.quantity}${item.unit}\n`;
      });
      
      alert(detailText);
    },
    
    // 取消出库记录
    cancelRecord(id) {
      if (confirm('确定要取消该出库记录吗？这将恢复相应库存。')) {
        const index = this.outboundRecords.findIndex(record => record.id === id);
        if (index !== -1) {
          // 恢复库存
          this.outboundRecords[index].items.forEach(item => {
            const consumableIndex = this.consumables.findIndex(
              c => c.name === item.name && c.specification === item.specification
            );
            if (consumableIndex !== -1) {
              this.consumables[consumableIndex].stock += item.quantity;
            }
          });
          
          // 更新状态
          this.outboundRecords[index].status = '已取消';
        }
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    }
  }
};
</script>

<style scoped>
.outbound-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1e5e8;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.icon-arrow-left::before {
  content: "←";
}

.page-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-card, .records-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: box-shadow 0.3s;
}

.form-card:hover, .records-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

h2 {
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.required {
  color: #e74c3c;
}

.outbound-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.form-group {
  flex: 1;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-size: 14px;
  color: #666;
}

.form-group input, 
.form-group select, 
.form-group textarea {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus, 
.form-group select:focus, 
.form-group textarea:focus {
  border-color: #3498db;
  outline: none;
}

.full-width {
  width: 100%;
}

.items-section {
  margin-top: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

h3 {
  color: #333;
  font-size: 16px;
  margin: 0;
}

.add-item-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 5px 10px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
  font-size: 14px;
}

.add-item-btn:hover {
  background: #2980b9;
}

.icon-plus {
  font-weight: bold;
}

.items-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 10px;
}

.items-table th,
.items-table td {
  padding: 10px 12px;
  text-align: left;
  border: 1px solid #f0f0f0;
}

.items-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.items-table td {
  font-size: 14px;
}

.items-table input,
.items-table select {
  width: 100%;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.delete-item-btn {
  padding: 4px 8px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background 0.3s;
  font-size: 13px;
}

.delete-item-btn:hover:not(:disabled) {
  background: #c0392b;
}

.delete-item-btn:disabled {
  background: #ec968a;
  cursor: not-allowed;
}

.error-text {
  display: block;
  color: #e74c3c;
  font-size: 12px;
  margin-top: 3px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.reset-btn {
  padding: 10px 20px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.reset-btn:hover {
  background: #f5f5f5;
}

.submit-btn {
  padding: 10px 20px;
  background: #2ecc71;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
  font-weight: 500;
}

.submit-btn:hover {
  background: #27ae60;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  width: 250px;
}

.search-btn {
  padding: 8px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.search-btn:hover {
  background: #2980b9;
}

.records-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.records-table th,
.records-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.records-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #333;
}

.records-table tr:hover {
  background-color: #f9fafb;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-completed {
  background-color: #eafaf1;
  color: #27ae60;
}

.status-canceled {
  background-color: #fdedeb;
  color: #e74c3c;
}

.view-btn {
  padding: 4px 8px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background 0.3s;
  font-size: 13px;
  margin-right: 5px;
}

.view-btn:hover {
  background: #2980b9;
}

.cancel-btn {
  padding: 4px 8px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 13px;
}

.cancel-btn:hover {
  background: #c0392b;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 10px;
}

.pagination button {
  padding: 5px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination button:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

.pagination button:disabled {
  color: #999;
  cursor: not-allowed;
}

.pagination span {
  color: #666;
}
</style>